package com.rabbitmq.example.retry;

import com.rabbitmq.example.retry.exception.RetryMessageException;
import com.rabbitmq.example.service.RetryMessageRabbitTemplate;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

@Aspect
public class RetryMessageAspect {

    public RetryMessageAspect(RetryMessageRabbitTemplate retryMessageService) {
        this.retryMessageService = retryMessageService;
    }

    private RetryMessageRabbitTemplate retryMessageService;

    @Pointcut("@annotation(com.rabbitmq.example.retry.RetrySendMessage)")
    public void logPointCut() {}



    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable{
        Signature signature = point.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        Parameter[] parameters = method.getParameters();

        Object[] args = point.getArgs();


        RetrySendMessage annotation = method.getAnnotation(RetrySendMessage.class);
        if (annotation == null) {
            return point.proceed();
        }else {
            Integer id = null;
            Integer exchange =null;
            Integer routingKey =null;
            Integer message =null;

            for(int i = 0;i < parameters.length ; i++) {
                if( parameters[i].getAnnotation(ID.class) != null) {
                    id = i;
                }
                if( parameters[i].getAnnotation(Message.class) != null) {
                    message = i;
                }
                if( parameters[i].getAnnotation(RoutingKey.class) != null) {
                    routingKey = i;
                }
                if(parameters[i].getAnnotation(Exchange.class) != null) {
                    exchange = i;
                }
            }

            if(id == null || message == null || exchange == null || routingKey == null) {
                throw new RetryMessageException("id  exchage  routingkey  为空了");
            }
            retryMessageService.saveToDB((String)args[id],args[message],(String)args[exchange],(String)args[routingKey]);
            return point.proceed();
        }
    }


}
